from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import backtrader as bt
from backtrader.utils.datehelper import *
from backtrader.utils import logger
from datetime import datetime


class StrategyBase(bt.Strategy):
    params = (
        ('timeframe', '1h'),
        ('comm', 10),
        ('leverage', 5),
        ('size', 95),
        ('init_cash', 20000),
        ('start_date', 20210101),
        ('ended_date', 20121117),
    )
    CLOSE, HLC3, HLOC4, VWAP = range(0, 4)

    def __init__(self):
        super(StrategyBase, self).__init__()
        self.logger = logger.getLogger(__name__)

    def log(self, label, symbol, txt, maker, bar_dt=None):
        ''' Logging function fot this strategy'''
        if bar_dt is None:
            bar_dt = datetime.today()
        if isinstance(bar_dt, float) or isinstance(bar_dt, int):
            bar_dt0 = datetime.fromtimestamp(int(bar_dt / 1000))
            if bar_dt0.year == 1970:
                bar_dt = bt.num2date(bar_dt)
            else:
                bar_dt = bar_dt0
        dt_str = bar_dt.strftime("%Y-%m-%d %H:%M:%S")
        print("[**%15s**], [%sbar: %s%s], [symbol: %s], [%s]" % (label, maker, dt_str, maker, symbol, txt))

    def format_simple(self, data):
        if not data._name.endswith("USDT"):
            return data._name[0:data._name.index("USDT") + len("USDT")]
        return data._name

    def notify_order(self, order):
        if order.status == order.Submitted:
            text = "Id: %2s, Type: %6s, 【Direc: %4s Submitted, Size: %9.4f, Price: %8.2f】, Limit %10.2f" % \
                   (order.ref,
                    order.getordername(),
                    order.ordtypename().upper(),
                    order.size,
                    order.price if order.price else 0,
                    order.pricelimit if order.pricelimit else 0)

            self.log("Order Submitted", order.data._name, text, "+++", order.created.dt)
            return
        if order.status == order.Canceled:
            text = "Id: %2s, Type: %6s, 【Direc: %4s Canceled , Size: %9.4f, Price: %8.2f】, Limit %10.2f" % \
                   (order.ref,
                    order.getordername(),
                    order.ordtypename().upper(),
                    order.size,
                    order.price if order.price else 0,
                    order.pricelimit if order.pricelimit else 0)

            self.log("Order Canceled ", order.data._name, text, "---", order.created.dt)
            return
        elif order.status in [order.Completed]:
            text = "Id: %2s, Type: %6s, 【Direc: %4s Completed, Size: %9.4f, Price: %8.2f】, Value %10.2f, Comm %2.4f" % \
                   (order.ref,
                    order.getordername(),
                    order.ordtypename().upper(),
                    order.executed.size,
                    order.executed.price,
                    order.executed.value,
                    order.executed.comm)
            self.log("Order Completed", order.data._name, text, "***", order.executed.dt)
        elif order.status in [order.Margin]:
            text = "Cash not enough, Id: %2s, Type: %5s, 【Direc: %4s, Size: %9.4f, Price: %8.2f】, Limit %10.2f" % \
                   (order.ref,
                    order.getordername(),
                    order.ordtypename().upper(),
                    order.size,
                    order.price if order.price else 0,
                    order.pricelimit if order.pricelimit else 0)
            self.log("Order Failed", order.data._name, text, "@@@", order.executed.dt)

